import requests
import json
import base64
import os
base_url = 'https://gitee.com/api/v5/repos'
access_token = 'cb2f59c560881af25e041de5c55536fb'
owner = "wx_4b5994c945" # 用户仓库名称
repo = "script-library"  # 仓库名称
branch = 'master' #分支名称
# 设置请求头，指定内容类型为JSON
headers = {
    'Content-Type': 'application/json'
}
# pages地址
oi = f"https://{owner}.gitee.io/" + repo
# 文件转base64
def file_to_base64(file_path):
    # 打开文件并读取其内容
    with open(file_path, "rb") as file:
        # 读取文件内容
        file_content = file.read()
        
        # 使用base64对文件内容进行编码
        base64_string = base64.b64encode(file_content).decode('utf-8')
        return base64_string
# 获取 pages信息
def getPages():
    url = base_url+ f'/{owner}/{repo}/pages'
    data = {
        'access_token':access_token
    }
    response = requests.get(url,params=data, headers=headers)
    # 检查请求是否成功
    if response.status_code == 200:
        # 获取响应内容
        content = response.json() 
        return content
    else:
        print(f'请求失败，状态码：{response.status_code}',response.json())  
# 获取仓库文件列表
def getFileList():
    url = f'https://gitee.com/{owner}/{repo}/file_list?ref=master'
    data = {
        'access_token':access_token
    }
    response = requests.get(url,params=data, headers=headers)
    # 检查请求是否成功
    if response.status_code == 200:
        # 获取响应内容
        content = response.json() 
        return content
    else:
        print(f'请求失败，状态码：{response.status_code}',response.json())  

# 根据地址获取仓库文件内容
def getFileContent(filePath):
    url = base_url + f'/{owner}/{repo}/contents/{filePath}'
    data = {
        'access_token':access_token,
    }
    response = requests.get(url,params=data, headers=headers)
    # 检查请求是否成功
    if response.status_code == 200:
        # 获取响应内容
        content = response.json() 
        return content
    else:
        print(f'请求失败，状态码：{response.status_code}',response.json())  


# 新增文件
def addFile(content,message,filePath):
    url = base_url + f'/{owner}/{repo}/contents/{filePath}'
    # 要发送的数据
    data = {
        'access_token':access_token,
        'content':content,
        'message':message
    }

    # 将数据转换为JSON格式
    json_data = json.dumps(data)
    
    
    print(url,filePath)
    
    response = requests.post(url,data=json_data, headers=headers)
    # 检查请求是否成功
    if response.status_code == 201:
        # 获取响应内容
        content = response.json() 
        return content
    else:
        print(f'请求失败，状态码：{response.status_code}',response.json())  
# 修改文件
def editFile(content,message,filePath):
    url = base_url + f'/{owner}/{repo}/contents/{filePath}'
    fileInfo = getFileContent(filePath)
    # 要发送的数据
    data = {
        'access_token':access_token,
        'content':content,
        'message':message,
        'sha':fileInfo['sha']
    }
    # 将数据转换为JSON格式
    json_data = json.dumps(data)
    response = requests.put(url,data=json_data, headers=headers)
    # 检查请求是否成功
    if response.status_code == 200:
        # 获取响应内容
        content = response.json() 
        return content
    else:
        print(f'请求失败，状态码：{response.status_code}',response.json())
def clear():
    # 清空仓库
    url = base_url + f'/{owner}/{repo}/clear'
    data = {
        'access_token':access_token,
    }
     # 将数据转换为JSON格式
    json_data = json.dumps(data)
    response = requests.put(url,data=json_data, headers=headers)
    # 检查请求是否成功
    if response.status_code == 201:
        # 获取响应内容
        content = response.json() 
        return content
    else:
        print(f'请求失败，状态码：{response.status_code}',response.json())
# 业务代码
fileList = getFileList()
# 等待上传文件
def upData(file_path = 'aaPng'):
    files = os.walk(file_path) 
   
    # 跟线上已经存在的文件进行对比，存在的文件进行修改，新增的文件进行新增
    for dirpath, dirnames, filenames in files :
        for element in filenames:
          
            fileName = f'{dirpath}/{element}'
            filePath = f'{dirpath}/{element}'.replace('\\','/').replace('./','')
            try:
                if filePath in fileList:
                    # 修改
                    editFile(file_to_base64(filePath),'修改'+element,filePath)
                elif not 'html' in element:
                    # 新增
                    addFile(file_to_base64(filePath),'新增'+element,filePath)
                
                print('同步成功：', element)
            except Exception as e:
                print('同步失败：', e)
                print('失败文件：', element)

upData('.')
# 清空仓库
# if(len(fileList)) clear()
